﻿using UnityEngine;
using System.Collections;

public class BallScript : MonoBehaviour {


	public float speed = 0.01f;
	public bool moving = false;
	private Rigidbody2D rb;
	private SpriteRenderer sp;

	public Sprite collided;
	public Sprite normal;

	public AudioClip wallBounce;
	public AudioClip paddleBounce;
	public AudioClip collectorSound;

	public ParticleSystem deathParticles;
	public ParticleSystem trailParticles;

	private AudioSource audioSource;

	// Use this for initialization
	void Start () {
		rb = GetComponent<Rigidbody2D> ();
		sp = GetComponent<SpriteRenderer> ();
		audioSource = GetComponent<AudioSource> ();
	}
	
	// Update is called once per frame
	void Update () {

	}

	public void startBall(float direction){
		this.moving = true;
		rb.AddForce(new Vector2 (speed * direction, speed * direction));
	}

	IEnumerator OnCollisionEnter2D(Collision2D collision){
		if (collision.gameObject.tag == "Paddle") {

			audioSource.PlayOneShot (paddleBounce);

			float y = hitFactor (transform.position,
			                     collision.transform.position,
			                     collision.collider.bounds.size.y);
			
			float xpos = collision.gameObject.name == "LeftPaddle" ? xpos = 1.0f : xpos = -1.0f;

			Vector2 dir = new Vector2 (xpos, y).normalized;

			rb.AddForce (dir * (speed / 5));

		} else if (collision.gameObject.tag == "BallCollector") {
			audioSource.PlayOneShot(collectorSound);
		} else {
			audioSource.PlayOneShot(wallBounce);
		}

		sp.sprite = collided;
		yield return new WaitForSeconds (0.1f);
		sp.sprite = normal;

	}

	float hitFactor(Vector2 ballPos, Vector3 racketPos,
	                float racketHeight) {
		return (ballPos.y - racketPos.y) / racketHeight;
	}

	public void playDeath(){
		trailParticles.Stop ();
		deathParticles.Play ();
		stopBall ();
	}

	public void stopBall(){
		this.rb.velocity = Vector2.zero;
	}

	public void reset(){
		this.moving = false;
		this.transform.position = new Vector2(0.0f, 0.0f);
		this.rb.velocity = Vector2.zero;
	}
}
